package rhc.discribute.node.connecter.impl.zookper.watchCallback;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;

import rhc.discribute.BaseComponent;
import rhc.discribute.node.connecter.impl.zookper.MyWatcher;
import rhc.discribute.node.connecter.impl.zookper.WatchCallback;
import rhc.discribute.node.connecter.impl.zookper.ZookperOperate;
import rhc.discribute.node.exception.CallbackException;

public class GetPathLockWatchCallback extends BaseComponent implements WatchCallback {

	private String secretCode;
	
	CountDownLatch latch;
	
	String path;
	
	public GetPathLockWatchCallback(String secretCode,CountDownLatch latch,String path){
		this.secretCode=secretCode;
		this.latch=latch;
		this.path=path;
	}
	
	@Override
	public void executeCallback(WatchedEvent event, Object callbackData) throws CallbackException {
		ZookperOperate zkOperate=(ZookperOperate) callbackData;
		
		if(event.getType() == EventType.NodeCreated){
			try {
				byte[] data=zkOperate.getPathData(path);
				String str=new String(data,"UTF-8");
				if(str.equals(secretCode)){
					latch.countDown();
					return;
				}
				//如果不是自己创建的则再次尝试创建
				createPath(zkOperate);
			} catch (KeeperException e) {
				createPath(zkOperate);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			//如果为其它事件则尝试创建
			createPath(zkOperate);
		}
	}

	@Override
	public boolean isSync() {
		return false;
	}
	
	/**尝试创建path
	 * @param zkOperate
	 */
	private void createPath(ZookperOperate zkOperate){
		
		try {
			zkOperate.watchPath(path, new MyWatcher(this,zkOperate,true),true);
			byte[] data=secretCode.getBytes("UTF-8");
			zkOperate.createPath(path, data, true, CreateMode.EPHEMERAL);
		} catch (Exception e) {
		}
	}

}
